package club.beimeng.emailserver2.controller;


import club.beimeng.emailserver2.entity.EmailAccount;
import club.beimeng.emailserver2.service.EmailAccountService;
import club.beimeng.emailserver2.utils.CheckEmailNumber;
import club.beimeng.emailserver2.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 小艾同学
 * @since 2021-09-29
 */
@RestController
@RequestMapping("/emailSever2/email-account")
public class EmailAccountController { // 提供账户的增删改查

    @Autowired
    private EmailAccountService emailAccountService;


    // 1 获取账户列表
    @GetMapping("getAccounts")
    public R getAccounts(){
        List<EmailAccount> emailAccounts = emailAccountService.list();
        if (emailAccounts != null && emailAccounts.size() != 0){
            return R.ok().data("emailAccounts",emailAccounts);
        }else
            return R.error();
    }

    // 2 获取单个账户
    @GetMapping("getAccountById")
    public R getAccountById(String accountId){
        EmailAccount emailAccount = emailAccountService.getById(accountId);
        if (emailAccount != null){
            return R.ok().data("emailAccount",emailAccount);
        }else
            return R.error();
    }
    // 3 通过id删除账户
    @DeleteMapping("deleteAccountById")
    public R deleteAccountById(String accountId){
        return emailAccountService.deleteAccountById(Long.parseLong(accountId));
    }

    // 4 添加账户
    @PostMapping("addAccount")
    public R addAccount(@RequestBody EmailAccount account){
        if (!CheckEmailNumber.check(account.getEmailNumber())){
            return R.error().message("邮件名称不合法");
        }
        return emailAccountService.addAccount(account);
    }

    // 5 修改账户
    @PutMapping("updateAccountById")
    public R updateAccountById(@RequestBody EmailAccount account){
        if (!CheckEmailNumber.check(account.getEmailNumber())){
            return R.error().message("新邮件名称不合法");
        }
        return emailAccountService.updateAccountById(account);
    }
}

